package com.galeno.day06;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.HashMap;
import java.util.Map;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2210:12
 */
public class MykeyStateDemo {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",55555);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        env.enableCheckpointing(1000);
        DataStreamSource<String> lines = env.socketTextStream("galeno", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> tuped = lines.map(x -> {
            String[] split = x.split(",");
            if (split[0].contains("error")) {
                throw new RuntimeException("出错重试");
            }
            return Tuple2.of(split[0], Integer.parseInt(split[1]));
        }).returns(TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {
        })).setParallelism(2);
        KeyedStream<Tuple2<String, Integer>, String> keyBy = tuped.keyBy(x -> x.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> map = keyBy.map(new MyReduceFunction());
        map.print();
        env.execute();


    }

    private static class MyReduceFunction extends RichMapFunction<Tuple2<String,Integer>,Tuple2<String,Integer>> {
       private Map<String,Integer> wordcount= new HashMap<String,Integer>();
        @Override
        public Tuple2<String, Integer> map(Tuple2<String, Integer> in) throws Exception {
            String word = in.f0;
            Integer currentCount = in.f1;
            Integer historyCount = wordcount.get(word);
            if (historyCount==null){
                historyCount=0;
            }
            int totalCount=historyCount+currentCount;
            wordcount.put(word,totalCount);
            in.f1=totalCount;
            return in;

        }
    }
}
